<template>
  <div class="main">
    <a-form
      id="formLogin"
      class="user-layout-login"
      ref="formLogin"
      :form="form"
      @submit="handleSubmit"
    >
      <a-tabs
        :activeKey="customActiveKey"
        :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
        @change="handleTabClick"
      >
        <a-tab-pane key="tab1" tab="账号密码登录">
          <a-form-item>
            <a-input
              size="large"
              type="text"
              placeholder="账户"
              v-decorator="[
                'userName',
                {rules: [{ required: true, message: '请输入用户名或手机号码' }], validateTrigger: 'change'}
              ]"
            >
              <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-item>

          <a-form-item>
            <a-input
              size="large"
              type="password"
              autocomplete="false"
              placeholder="密码"
              v-decorator="[
                'userPassword',
                {rules: [{ required: true, message: '请输入密码' }], validateTrigger: 'blur'}
              ]"
            >
              <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-item>
          <a-row :gutter="16" >
            <a-col class="gutter-row" :span="16">
              <a-form-item>
                <a-input size="large" type="text"  placeholder="图片验证码" v-decorator="['imgCode1', {rules: [{ required: true, message: '请输入图片验证码' }], validateTrigger: 'blur'}]">
                  <a-icon slot="prefix" type="picture" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <img :src="imgSrc" @click="initCode" mode="" class="getCaptcha"/>
            </a-col>
          </a-row>
        </a-tab-pane>
        <a-tab-pane key="tab2" tab="手机号登录">
          <a-form-item>
            <a-input size="large" type="text" placeholder="手机号" v-decorator="['cellphone', {rules: [{ required: true, pattern: /^1[34578]\d{9}$/, message: '请输入正确的手机号' }], validateTrigger: 'change'}]">
              <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-item>
          <a-row :gutter="16">
            <a-col class="gutter-row" :span="16">
              <a-form-item>
                <a-input size="large" type="text" @change="imgCodeChange" placeholder="图片验证码" v-decorator="['imgCode', {rules: [{ required: true, message: '请输入图片验证码' }], validateTrigger: 'blur'}]">
                  <a-icon slot="prefix" type="picture" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <img :src="imgSrc" @click="initCode" mode="" class="getCaptcha"/>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col class="gutter-row" :span="16">
              <a-form-item>
                <a-input size="large" type="text" placeholder="验证码" v-decorator="['shortMsgCode', {rules: [{ required: true, message: '请输入验证码' }], validateTrigger: 'blur'}]">
                  <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-button
                class="getCaptcha"
                tabindex="-1"
                :disabled="disableCodeBtn"
                @click.stop.prevent="getCaptcha"
                v-text="!state.smsSendBtn && state.smsText || (state.time+' s')"
              ></a-button>
            </a-col>
          </a-row>
        </a-tab-pane>
      </a-tabs>
      <a-form-item style="margin-top:24px">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="login-button"
          :loading="state.loginBtn"
          :disabled="state.loginBtn"
        >确定</a-button>
      </a-form-item>
      <a-form-item>
        <router-link class="register" :to="{ name: 'register',query:{userType:userType} }" >注册账户</router-link>
        <div style="float: right;">
          <router-link
            :to="{ name: 'forgePassword',query:{userType:userType} }"
            class="forge-password"
          >忘记密码</router-link>
        </div>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import md5 from 'md5'
import store from '@/store'
import { mapActions } from 'vuex'
import { getBrowerInfo, uuid } from '@/utils/util'
import { loginSendMessage,getImgCode} from "@/services/system/api"
export default {
  data () {
    return {
      customActiveKey: 'tab1',
      loginBtn: false,
      loginType: 'username',
      isLoginError: false,
      disableCodeBtn: true,
      imgSrc: '',
      loginKey: uuid(),
      userType:'10',
      showImgCode:false,
      browser: getBrowerInfo(),
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 6 email, 1 username, 2 telephone
        loginType: 6,
        smsSendBtn: false,
        smsText: '获取验证码'
      }
    }
  },
  created () {
    this.initCode()
    // this.requiredTwoStepCaptcha = true
  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    initCode () {
      const url = getImgCode +'?loginKey='+ this.loginKey + '&time=' + new Date().getTime()
      this.imgSrc = url
    },
    imgCodeChange (e) {
      const imgCode = e.target.value || ''
      if (this.state.smsSendBtn) {
        this.disableCodeBtn = true
        return
      }
      if (imgCode.length < 4) {
        this.disableCodeBtn = true
      } else {
        this.disableCodeBtn = false
      }
    },
    handleTabClick (key) {
      this.customActiveKey = key
      const params ={}
      params.imgCode=''
      params.imgCode1=''
      setTimeout(()=>{
        this.form.setFieldsValue(params)
      },100)
      this.initCode()
      if(key=='tab2'){
        this.loginType='cellphone'
      }else if(key=='tab1'){
        this.loginType='username'
      }
      // this.form.resetFields()
    },
    handleSubmit (e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
        customActiveKey,
        Login,
        loginType,
        loginKey,
        userType,
        browser
      } = this
      state.loginBtn = true
      const validateFieldsKey = customActiveKey === 'tab1' ? ['userName', 'userPassword', 'imgCode1'] : ['cellphone', 'shortMsgCode', 'imgCode']
      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {          
          const loginParams={}
          loginParams.loginType = loginType
          loginParams.userType=userType
          loginParams.equipmentType = 'pc'
          loginParams.browser = browser.browserType
          loginParams.loginKey = loginKey
          loginParams.version = store.state.version
					loginParams.systemCode = store.state.systemCode
					loginParams.systemName = store.state.systemName
          if (loginType=='username'){
            loginParams.userPassword = md5(values.userPassword)
            loginParams.userName=values.userName
            loginParams.imgCode=values.imgCode1
          }else if(loginType=='cellphone'){
            loginParams.cellphone=values.cellphone
            loginParams.shortMsgCode=values.shortMsgCode
            loginParams.imgCode=values.imgCode
          }
          Login(loginParams)
            .then((res) => this.loginSuccess(res))
            .catch(err => this.requestFailed(err))
            .finally(() => {
              state.loginBtn = false
            })
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },
    getCaptcha (e) {
      e.preventDefault()
      const { form: { validateFields }, state } = this
      validateFields(['cellphone', 'imgCode'], { force: true }, (err, values) => {
        if (!err) {
          state.smsSendBtn = true
          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60
              state.smsSendBtn = false
              state.smsText = '重新发送'
              window.clearInterval(interval)
            }
          }, 1000)
          const hide = this.$message.loading('验证码发送中..', 0)
          const data = {}
          data.cellphone = values.cellphone
          data.imgCode = values.imgCode
          data.loginKey = this.loginKey
          this.$http.post(loginSendMessage,data).then(() => {
            setTimeout(hide, 100)
            this.$notification['success']({
              message: '提示',
              description: '发送短信验证码成功',
              duration: 4
            })
          }).catch(err => {
            setTimeout(hide, 1)
            clearInterval(interval)
            state.time = 60
            state.smsSendBtn = false
            state.smsText = '获取验证码'
            this.requestFailed(err)
          })
        }
      })
    },
    stepCaptchaSuccess () {
      this.loginSuccess()
    },
    stepCaptchaCancel () {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    loginSuccess (res) {
      console.log(res)
      // check res.homePage define, set $router.push name res.homePage
      // Why not enter onComplete
      /*
      this.$router.push({ name: 'analysis' }, () => {
        console.log('onComplete')
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      })
      */
      this.$router.push({ name: 'userManager' })
      // 延迟 1 秒显示欢迎信息
      /**
      setTimeout(() => {
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      }, 1000)
      */
      this.isLoginError = false
    },
    requestFailed (error) {
      this.isLoginError = true
      if(error.code == 40101){
					this.showImgCode = true
					this.initCode()
			}
    }
  }
}
</script>

<style lang="less" scoped>
.user-layout-login {
  label {
    font-size: 14px;
  }
  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }
  .forge-password {
    font-size: 14px;
  }
  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }
  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;
    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;
      &:hover {
        color: #1890ff;
      }
    }
    .register {
      float: left;
    }
  }
}
</style>
